import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
  Inject,
} from '@nestjs/common';
import { getExceptionByStatusCode, sendExceptionResponse } from 'src/utils';
import {
  EntityNotFoundError,
  EntityPropertyNotFoundError,
  QueryFailedError,
} from 'typeorm';

@Catch(QueryFailedError, EntityPropertyNotFoundError, EntityNotFoundError)
export class TypeOrmExceptionFilter implements ExceptionFilter {
  // constructor(@Inject(WINSTON_LOGGER_TOKEN) private readonly logger: CustomLogger) {}
  catch(exception: QueryFailedError, host: ArgumentsHost) {
    console.log('TypeOrmExceptionFilter:', exception.message);
    const request = host.switchToHttp().getRequest();
    const response = host.switchToHttp().getResponse();
    const statusCode = HttpStatus.INTERNAL_SERVER_ERROR; // 你可以根据需要修改状态码

    const errorResponse = exception.driverError;
    console.log('errorResponse:', errorResponse);
    const errMessage =
      'Database connection error or query failed,' + exception.message;

    //通过statusCode获取标准的http error名称，比如Not Found ,Conflict ...
    const errorName = getExceptionByStatusCode(statusCode).error;
    // console.log('errorName:', errorName);

    // 发送异常响应
    sendExceptionResponse({
      response, // 响应对象
      statusCode: statusCode, // 状态码
      errorName, // 错误名称/类型
      message: errMessage, // 错误信息
      detail: exception.driverError,
      exception: {},
    });
    // this.logger.error(exception.driverError.message, { context: 'TypeormError', url: request.url, method: request.method, statusCode });
  }
}
